package ;

#if php
import haxe.Http;
import haxe.PosInfos;
import php.io.File;
import php.Lib;
import php.Session;
import php.Web;
import php.Cart;
#end

using me.cunity.tools.StringTool;
/**
 * ...
 * @author Axel Huizinga axel@cunity.me
 */

class Server 
{
	
	var cart:Cart;
	
	static function main() 
	{
		var ctx = new haxe.remoting.Context();
		ctx.addObject("Server",new Server());
		if( haxe.remoting.HttpConnection.handleRequest(ctx) )
		  return;
		// handle normal request
		#if php
		Lib.print("This is a remoting server !");
		#end
	}
	
	function new() 
	{ 
	}
	
	public function add(a:Dynamic, b:Dynamic):Dynamic
	{
		//trace(a +':' + b);
		untyped __call__("error_log", a +':' +  b +  '->' + (a + b));
		return a + b;
	}
	
	public function addMany(a:Array<Dynamic>)
	{ 
		var result = (a.length == 0) ? 0 : a.pop();
		while (a.length > 0)
			result = add(result, a.pop());
		untyped __call__("error_log",   '->' + result);
		return result; 
	}
	
	public function initSession(clientDate:String):Hash<String>
	{
		#if php
		errLog('Session.started:' + Std.string(Session.started));
		var response:Hash<String> = null;
		
		var site:String = Web.getHostName() +  Web.getURI().dirname();
		if (!Session.started)
			Session.start();
		
		if (Session.get('Site') != site && Session.getId() != Web.getCookies().get('Session'))
		{
			//Session initialization 
			Session.set('Site', site);
			Session.set('ip', Web.getClientIP());
			Session.set('sessionStartTime', clientDate);
			Session.set('serverStartTime', new DateFormat().text);
		/*	try{
				var cartData:Xml = Xml.parse(File.getContent('site/cart.xml'));
				cart = new Cart(cartData);
			}
			catch (ex:Dynamic)
			{
				errLog("Konnte Warenkorb nicht für die Serverseitige Speichernung vorbereiten");
			}*/

		}
		else
		{
			Session.set('clientTime', clientDate);
			var cookieKeys:String = '';
			var it:Iterator<String> = Web.getCookies().keys();
			while (it.hasNext())
				cookieKeys += it.next() + ',';
			errLog(Session.getName() +':' + cookieKeys);
			var ses:Dynamic = Web.getCookies().get(Session.getName());
			errLog(Std.string(ses));
			
		}
			
		Session.set('clientTime', clientDate);
		response = Lib.hashOfAssociativeArray(untyped __var__('_SESSION'));
		response.set('apiMethod', 'initSession');
		return response;
		#else
		return null;
		#end
		
	}
	
	public function checkout(data:Hash<String>)
	{
		
	}
	
	public function saveSession()
	{
		#if php
		errLog('closing Session @ip:' + Session.get('ip'));
		#end
	}
	
	#if php
	
	function errLog(m:String, ?i:PosInfos)
	{
		var msg = if( i != null ) i.lineNumber+": "  + i.methodName  else "";
		untyped __call__("error_log",   msg +':' + m);
	}
	
	public function add2cart(id:String, count:Int)
	{
		Session.set(id,  (Session.get(id) == null) ? count : Session.get(id) + count);
	}
	#end


}